#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

size_t readline(int fd)
{
    char c;
    size_t bytes = 0;

	printf("> ");
    while(read(fd, &c, 1))
    {
        if (c == '\r')
            continue;
        if (c == '\n')
            break;
        putchar(c);
        bytes++;
    }
    printf("\n");

    return bytes;
}

ssize_t writeline(int fd, char* line)
{
	size_t bytes = 0;
	bytes += write(fd, line, strlen(line));
	bytes += write(fd, "\r\n", 2);
	printf("< %s\n", line);
	return bytes;
}

int main()
{
	int sfd;

	sfd = socket(PF_INET, SOCK_STREAM, 0);
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr("14.18.175.202");
	addr.sin_port = htons(25);
	connect(sfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));

	readline(sfd);
	writeline(sfd, "HELO localhost");
	readline(sfd);
	readline(sfd);
	readline(sfd);
	writeline(sfd, "AUTH LOGIN");
	readline(sfd);
	writeline(sfd, "OTY1NDI0NTcy");
	readline(sfd);
	writeline(sfd, "cHRwYmtoYXZzcWJ0YmZhag==");
	readline(sfd);
	writeline(sfd, "MAIL FROM:<tinytaro@qq.com>");
	readline(sfd);
	writeline(sfd, "RCPT TO:<geez@163.com>");
	readline(sfd);
	writeline(sfd, "DATA");
	readline(sfd);
	writeline(sfd, "From: \"LIU Yu\" <tinytaro@qq.com>");
	writeline(sfd, "To: <geez@163.com>");
	writeline(sfd, "Subject: Hello from Mail client");
	writeline(sfd, "");
	writeline(sfd, "Hello from smtp.c");
	writeline(sfd, "");
	writeline(sfd, ".");
	readline(sfd);
	writeline(sfd, "QUIT");

	close(sfd);
	return 0;
}
